package cn.imatu.framework.log.core.filter;

import brave.baggage.BaggageField;
import cn.imatu.framework.log.common.LogCons;
import cn.imatu.framework.tool.core.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 在请求链路中添加用户标识
 * @author shenguangyang
 */
@Slf4j
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomTraceUserFilter implements Filter {
    @Resource
    private CustomTraceUser customTraceUser;
    @Resource
    private BaggageField loginIdField;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        try {
            String loginId = httpRequest.getHeader(LogCons.LOGIN_ID);
            if (StringUtils.isEmpty(loginId)) {
                loginId = customTraceUser.getLoginId();
            }
            loginId = StringUtils.defaultString(loginId, "-");
            loginIdField.updateValue(loginId);
        } catch (Exception e) {
            log.error("error: ", e);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}
